# -*- coding: utf-8 -*-
from scrapy import Request
from zc_core.model.items import Box
from szecp.rules import *
from zc_core.spiders.base import BaseSpider


class MetaSpider(BaseSpider):
    name = 'meta'
    # 常用链接
    cat_url = 'https://szecp.crc.com.cn/srm/api/smal/v1/968/com-catalog/visit-storeList?companyId=1021'
    supplier_url = 'https://szecp.crc.com.cn/srm/api/smal/v1/ec-platforms/labels?companyId=1021&tenantId=968'

    def __init__(self, batchNo=None, *args, **kwargs):
        super(MetaSpider, self).__init__(batchNo=batchNo, *args, **kwargs)

    def start_requests(self):
        # 品类
        yield Request(
            url=self.cat_url,
            meta={
                'batchNo': self.batch_no,
            },
            callback=self.parse_catalog,
            errback=self.error_back,
            priority=250,
            dont_filter=True,
        )
        # 供应商
        yield Request(
            url=self.supplier_url,
            meta={
                'batchNo': self.batch_no,
            },
            callback=self.parse_supplier,
            errback=self.error_back,
            priority=250,
            dont_filter=True,
        )

    def parse_catalog(self, response):
        cats = parse_catalog(response)
        if cats:
            self.logger.info('品类: count=%s' % len(cats))
            yield Box('catalog', self.batch_no, cats)
        else:
            self.logger.error('无品类')

    def parse_supplier(self, response):
        suppliers = parse_supplier(response)
        if suppliers:
            self.logger.info('供应商: count=%s' % len(suppliers))
            yield Box('supplier', self.batch_no, suppliers)
        else:
            self.logger.error('无供应商')
